package com.baizhi.element.controller;

import com.alibaba.druid.util.StringUtils;
import com.baizhi.element.dao.UserDao;
import com.baizhi.element.pojo.Result;
import com.baizhi.element.pojo.User;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("user")
@CrossOrigin
public class UserController {

    @Autowired
    UserDao userDao;

    @GetMapping("findAll")
    public Result findAll(){
        List<User> users = userDao.selectList(null);
        Integer count = userDao.selectCount(null);


        return new Result(0,"",count,users);
    }

    @PostMapping("saveOrUpdate")
    public Result saveOrUpdate(@RequestBody User user){
        Result result = new Result();
        System.out.println(user);

        try{
            if("".equals(user.getId())||user.getId()==null){
                userDao.insert(user);
                result.setMsg("保存用户成功");
                result.setCode(0);
            }else{
                userDao.updateById(user);
                result.setMsg("修改用户成功");
                result.setCode(0);
            }
        }catch (Exception e){
            result.setMsg("保存用户失败");
            result.setCode(1);
        }
        return result;
    }


    @GetMapping("delete")
    public Result delete(Integer id){
        Result result = new Result();
        try{
            userDao.deleteById(id);
            result.setCode(0);
            result.setMsg("删除用户成功");
        }catch(Exception e){
            result.setCode(1);
            result.setMsg("删除用户失败");
        }

        return result;
    }


    @GetMapping("findByPage")
    public Result findByPage(Integer page,Integer size){
        Result result = new Result();

        page=page==null?1:page;
        size=size==null?4:size;

        Page<User> objectPage = new Page<>(page,size);

        Page<User> userPage = userDao.selectPage(objectPage, null);
        long total = userPage.getTotal();
        result.setCount(6);
        result.setData(userPage.getRecords());

        return result;

    }


}
